package com.slkj.shilixiaoyuanapp.ui.main.community;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.slkj.shilixiaoyuanapp.BuildConfig;
import com.slkj.shilixiaoyuanapp.R;
import com.slkj.shilixiaoyuanapp.base.ActivityInfo;
import com.slkj.shilixiaoyuanapp.base.BaseActivity;
import com.slkj.shilixiaoyuanapp.entity.ToolLocationEntity;
import com.slkj.shilixiaoyuanapp.entity.code.UiCode;
import com.slkj.shilixiaoyuanapp.entity.contacts.ContactsPeopleEntity;
import com.slkj.shilixiaoyuanapp.net.CommonResult;
import com.slkj.shilixiaoyuanapp.net.HttpHeper;
import com.slkj.shilixiaoyuanapp.net.callback.BaseFunctionCallBack;
import com.slkj.shilixiaoyuanapp.net.callback.CommonCallBack;
import com.slkj.shilixiaoyuanapp.ui.common.ChoseObjActivity;
import com.slkj.shilixiaoyuanapp.ui.common.ChoseObjActivity__JumpCenter;
import com.slkj.shilixiaoyuanapp.ui.find.SendCirclePicAdapter;
import com.slkj.shilixiaoyuanapp.ui.teacher.tool.PunchClock.ChosePosMapActivity;
import com.slkj.shilixiaoyuanapp.util.UpdataFileUtil;
import com.slkj.shilixiaoyuanapp.util.picture.FileUtils;
import com.slkj.shilixiaoyuanapp.util.picture.TakePictureUtils;
import com.slkj.shilixiaoyuanapp.view.DialogProvider;
import com.slkj.shilixiaoyuanapp.view.dialog.LoadSuccessAndFailDialog;
import com.tkk.api.RxEventProcessor;
import com.tkk.api.annotation.Recipient;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindColor;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.ObservableSource;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;

import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.CHOSE_SEND_OBJ_FINSH;
import static com.slkj.shilixiaoyuanapp.entity.code.RxEventProcessorTag.TOOL_CHOSE_POSTION_FINSH;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_MAX_SIZW;
import static com.slkj.shilixiaoyuanapp.entity.code.UiCode.CHOSE_PIC_SPAN_COUNT;
import static com.slkj.shilixiaoyuanapp.ui.common.ChoseObjActivity.getCheckConstactsByGroup;

@RuntimePermissions
@ActivityInfo(layout = R.layout.activity_send_circle, rightHint = "发表")
public class SendCircleActivity extends BaseActivity implements SendCirclePicAdapter.OnAddPicListener {
    @BindView(R.id.et_send_circle_content)
    EditText numberEditText;
    @BindView(R.id.recyc_pic)
    RecyclerView picRecyclerView;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    ArrayList<String> picPaths = new ArrayList<>();
    SendCirclePicAdapter adapter;
    BaseQuickAdapter readAdapter;

    public TakePictureUtils takePictureUtils;
    ArrayList<ContactsPeopleEntity> contactsAll = new ArrayList<>();
    ArrayList<ContactsPeopleEntity> contactsCheck = new ArrayList<>();
    public static final String tag = "SendCircleActivity";
    @BindView(R.id.img_pos)
    ImageView imgPos;
    @BindView(R.id.img_read)
    ImageView imgRead;
    @BindView(R.id.tv_people)
    TextView tvRead;
    @BindView(R.id.recycer_read)
    RecyclerView recycerRead;
    @BindColor(R.color.color_text_666)int color666;
    @BindColor(R.color.colorAccent)int colorAccent;

    @Override
    protected void init() {
        RxEventProcessor.get().bind(this);
        recycerRead.setLayoutManager(new GridLayoutManager(this,5));
        picRecyclerView.setLayoutManager(new GridLayoutManager(this, CHOSE_PIC_SPAN_COUNT));
        adapter = new SendCirclePicAdapter(this, picPaths, UiCode.CHOSE_PIC_MAX_SIZW);
        readAdapter = new BaseQuickAdapter<ContactsPeopleEntity, BaseViewHolder>(R.layout.item_send_community_read_people, contactsCheck) {
            @Override
            protected void convert(BaseViewHolder helper, ContactsPeopleEntity item) {
                ImageView imageView = helper.getView(R.id.img);
                Glide.with(SendCircleActivity.this).load(item.getHead()).into(imageView);
            }
        };
        picRecyclerView.setAdapter(adapter);
        recycerRead.setAdapter(readAdapter);
        takePictureUtils = TakePictureUtils.Builder.from(this).isCompressor(false).isTailor(false).creat();
        takePictureUtils.setTakeCallBacklistener(new TakePictureUtils.TakePictureListener() {
            @Override
            public void successful(File outFile) {
                picPaths.add(outFile.getPath());
                adapter.notifyItemInserted(picPaths.size());
            }

            @Override
            public void failed(int errorCode, List<String> deniedPermissions) {
            }
        });
        adapter.setListener(this);
    }

    @Override
    protected void onRightTitleClick() {
        String body = numberEditText.getText().toString();
        if (TextUtils.isEmpty(body)){
            showToast("请输入发布内容");
            return;
        }
        UpdataFileUtil.UpImgObservable("classDynamic", picPaths)
                .flatMap(new BaseFunctionCallBack<List<String>, Object>() {
                    @Override
                    public ObservableSource<CommonResult<Object>> back(List<String> result) {
                        String img = com.slkj.shilixiaoyuanapp.util.StringUtils.listToString(result);
                        return HttpHeper.get().toolService().addCommunity(body, tvAddress.getText().toString(), ChoseObjActivity.getIds(contactsCheck).toString(), img);
                    }
                })
                .compose(getThread())
                .compose(bindToLifecycle())
                .subscribe(new CommonCallBack<Object>(true,SendCircleActivity.this) {
                    @Override
                    public void onCallBackSuccess(Object data) {
                        LoadSuccessAndFailDialog.showSuccess(SendCircleActivity.this,"发表成功");
                        finish();
                    }
                });
    }

    @OnClick(R.id.layout_chose_address)
    void chosePos() {
        SendCircleActivityPermissionsDispatcher.onHaveLocPermissionWithPermissionCheck(SendCircleActivity.this);
    }

    @OnClick(R.id.layout_chose_people)
    void chosePeople() {
        ChoseObjActivity__JumpCenter.builder(this)
                .setMaxNum(10)
                .setTag(tag).setContacts(contactsAll).create().go();
    }

    /**
     * 选择位置成功
     *
     * @param locationEntity
     */
    @Recipient(tag = TOOL_CHOSE_POSTION_FINSH)
    void onPosChecked(ToolLocationEntity locationEntity) {
        tvAddress.setText(locationEntity.getTitle());
        imgPos.setColorFilter(colorAccent);
    }

    /**
     * 选择提醒谁看成功
     */
    @Recipient(tag = tag + CHOSE_SEND_OBJ_FINSH)
    void onPeopleCheck(ArrayList<ContactsPeopleEntity> back) {
        contactsAll.clear();
        contactsAll.addAll(back);
        contactsCheck.clear();
        contactsCheck.addAll(getCheckConstactsByGroup(back));
        if (contactsCheck.isEmpty()){
            tvRead.setText("");
            imgRead.setColorFilter(color666);

        }else {
            imgRead.setColorFilter(colorAccent);
            tvRead.setText("提醒谁看");
            readAdapter.notifyDataSetChanged();

        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        RxEventProcessor.get().unBind(this);
    }

    //照片数据回调
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        takePictureUtils.attachToActivityForResult(requestCode, resultCode, data);
        if (requestCode == UiCode.CHOSE_PIC_CODE && resultCode == RESULT_OK) {
            List<Uri> mSelected = Matisse.obtainResult(data);
            for (int i = 0; i < mSelected.size(); i++) {
                String filePath = FileUtils.getPathByUri(this, mSelected.get(i));
                picPaths.add(filePath);
            }
            adapter.notifyItemRangeInserted(picPaths.size(), mSelected.size());
        }
    }

    //照片权限
    @NeedsPermission({Manifest.permission.CAMERA})
    void onAgreePermission() {
        Matisse.from(SendCircleActivity.this)
                .choose(MimeType.ofImage())
                .countable(true)
                .maxSelectable(CHOSE_PIC_MAX_SIZW - picPaths.size())
                .captureStrategy(new CaptureStrategy(true, BuildConfig.APPLICATION_ID + ".fileprovider"))
                .imageEngine(new GlideEngine())
                .forResult(UiCode.CHOSE_PIC_CODE);
    }

    @OnPermissionDenied({Manifest.permission.CAMERA})
    void onDeniedPermission() {
        showToast("读取照片权限获取失败");
    }

    //照片权限回调
    @SuppressLint("NeedOnRequestPermissionsResult")
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        takePictureUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
        SendCircleActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
    }

    @NeedsPermission({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void onHaveLocPermission() {
        startActivity(ChosePosMapActivity.class);
    }

    @OnPermissionDenied({Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION})
    void onLocPermissionDenied() {
        showToast("请开启定位权限...");
    }

    //添加照片
    @Override
    public void onAddClick() {
        DialogProvider.getPhotoDialog(this, new DialogProvider.TakePicTypeListener() {
            @Override
            public void takePhoto() {
                takePictureUtils.getByCarema();
            }

            @Override
            public void chosePhoto() {
                SendCircleActivityPermissionsDispatcher.onAgreePermissionWithPermissionCheck(SendCircleActivity.this);
            }
        });
    }

}
